package com.gae101.service;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;

import com.google.android.gcm.demo.server.Datastore;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Sender;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

public class GcmServiceImpl implements GcmService {
	private static final Logger log = Logger.getLogger(GcmServiceImpl.class.getName());

	private static final String ENTITY_KIND = "Settings";
	private static final String ENTITY_KEY = "MyKey";
	private static final String ACCESS_KEY_FIELD = "ApiKey";
	
	@Override
	public void sendAll(String message) throws ServletException {
	    User user = UserServiceFactory.getUserService().getCurrentUser();
	    String userId = user.getUserId();
	    
		List<String> tokens = Datastore.getDevices();
		if (tokens.size() < 1) {
			log.info("no regId");
			return;
		}
		
		send(message, tokens);
	}

	@Override
	public void send(String message, List<String> tokens)
			throws ServletException {
	    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    
		// get gcm api key
		Key apiKey = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY);
	    Entity entity;
	    try {
	      entity = datastore.get(apiKey);
	    }
	    catch(EntityNotFoundException e) {
	    	log.severe("no apiKey");
	    	return;
	    }

	    String key = (String) entity.getProperty(ACCESS_KEY_FIELD);
	    Sender sender = new Sender(key);
		
		Message message1 = new Message.Builder().addData("message", message).build();
		  
	    try {
			MulticastResult result = sender.send(message1, tokens, 3);
			log.info(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
}
